const path = require('path');
const changeCase = require('change-case');
const errorMsg = require('./error-msg');
const util = require('./util');

const rootPath = util.searchPackageJSONDir(__dirname);

exports.lnitFiles = async (source) => {
  let lintResult = [];
  let files = await util.getAllFiles(source);
  files.forEach(file => {
    let fullpath = path.resolve(rootPath, file);
    let ext = path.extname(file);
    let basename = path.basename(file, ext);

    // 检查 kebabCase
    let kebabCaseName = changeCase.paramCase(basename);
    if (kebabCaseName !== basename) {
      lintResult.push(generateFilenameInvalidLog(fullpath, file, ext, kebabCaseName, basename));
    }

    // 检查路径是否重复
    let pathCaseName = changeCase.pathCase(basename);
    let duplicateSections = getDuplicateSection(file, pathCaseName);
    if (duplicateSections.length) {
      let _pathCaseName = pathCaseName.split('/');
      for (let i = duplicateSections.length; i--;) {
        _pathCaseName.splice(duplicateSections[i].index, 1);
      }
      kebabCaseName = changeCase.paramCase(_pathCaseName.join('/'));
      lintResult.push(generateDuplicatePathLog(fullpath, file, ext, kebabCaseName, basename));
    }
  });
  return lintResult;
}

function generateFilenameInvalidLog (fullpath, file, ext, expect, but) {
  return {
    ...errorMsg['filenameInvalid'],
    fullpath,
    file,
    ext,
    expect,
    but
  };
}

function generateDuplicatePathLog (fullpath, file, ext, expect, but) {
  return {
    ...errorMsg['duplicatePath'],
    fullpath,
    file,
    ext,
    expect,
    but
  };
}

function getDuplicateSection (source, dest) {
  let result = [];
  let _soucre = source.split('/');
  let _dest = dest.split('/');
  _dest.forEach((section, index) => {
    if (_soucre.indexOf(section) !== -1) {
      result.push({
        index,
        section
      });
    }
  });
  return result;
}
